package com.shuaiche.yeguan.ui.select;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.shuaiche.yeguan.R;
import com.shuaiche.yeguan.SCApplication;
import com.shuaiche.yeguan.config.HttpUrl;
import com.shuaiche.yeguan.model.SCCarBrandResponse;
import com.shuaiche.yeguan.model.SCCarBrandSelectModel;
import com.shuaiche.yeguan.net.http.HttpCallBack;
import com.shuaiche.yeguan.net.http.HttpHelper;
import com.shuaiche.yeguan.util.GetJsonDataUtil;
import com.shuaiche.yeguan.views.SCCustomDrawerLayout;
import com.shuaiche.yeguan.views.brandselectbar.BrandAdapter;
import com.shuaiche.yeguan.views.brandselectbar.ItemBean;
import com.shuaiche.yeguan.views.brandselectbar.decoration.SectionDecoration;
import com.shuaiche.yeguan.views.brandselectbar.decoration.TitleItemDecoration;
import com.shuaiche.yeguan.views.brandselectbar.second.SCSecondRightSelectViewAdapter;
import com.shuaiche.yeguan.views.brandselectbar.third.SCThirdRightSelectViewAdapter;
import com.shuaiche.yeguan.views.brandselectbar.widget.IndexBar;
import com.shuaiche.yeguan.views.dialog.LoadingDialog;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import static com.shuaiche.yeguan.util.GetJsonDataUtil.parseData;

public class SelectBrandsActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int REQUEST_CODE_FOR_CAR_CHOOSE = 1009;
    private RelativeLayout rl_back;
    private SCCustomDrawerLayout secondDrawerLayout;
    private LinearLayout llSecondContent;

    private SCCustomDrawerLayout thirdDrawerLayout;
    private LinearLayout llthirdContent;

    /**
     * 三个不限
     */
    private TextView tvSeries;
    private TextView tvSpecies;


    /**
     * 保存文件里的品牌数据
     */
    private SCCarBrandSelectModel carBrandSelectModel;
    /**
     * 横向列表
     * 推荐或历史的品牌
     */
    private List<SCCarBrandResponse> recommendBrands;

    private RecyclerView firstListView;
    private BrandAdapter firstAdapter;
    private LinearLayoutManager mFirstManager;
    private LinearLayoutManager mSecondManager;
    private LinearLayoutManager mThirdManager;

    private RecyclerView secondListView;
    private SCSecondRightSelectViewAdapter secondAdapter;
    private RecyclerView thirdListView;
    private SCThirdRightSelectViewAdapter thirdAdapter;
    /**
     * 显示指示器DialogText
     */
    private TextView mTvSideBarHint;
    /**
     * 右侧边栏导航区域
     */
    private IndexBar mIndexBar;
    private final static int FIRST = 1;
    private final static int SECOND = 2;
    private final static int THIRD = 3;
    private int requestTpye = 1;

    private List<ItemBean> mBrands = new ArrayList<>();
    private List<ItemBean> mSeconds = new ArrayList<>();
    private List<ItemBean> mThirds = new ArrayList<>();
    private ItemBean brand;     //选择的品牌
    private ItemBean series;    //选择的车系
    private ItemBean species;   //选择的款式

    /**
     * 如果来自添加车辆，则必须选择三层数据
     * 隐藏"不限"字段
     */
    private boolean isFromAddCar = false;
    private String from = "";
    /**
     * 来自订阅
     * 品牌 没有 "不限"
     */
    private boolean isFromSub = false;

    /**
     * 来自客户意向
     */
    private boolean isFromIntention = false;

    // 是否显示品牌的不限
    private boolean isBrandLimit = false;

    private LoadingDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Window window = getWindow();
        window.getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        );

        setContentView(R.layout.activity_select_brands);

        loadingDialog = new LoadingDialog(this,"加载中");
        getData();
        initViews();
    }

    private void getData() {
        if (getIntent() != null) {
            isFromAddCar = getIntent().getBooleanExtra("isFromAddCar", false);
            from = getIntent().getStringExtra("from");
            isBrandLimit = getIntent().getBooleanExtra("isBrandLimit", false);
//            isFromSub = getArguments().getBoolean("isFromSub", false);
//            isFromIntention = getArguments().getBoolean("isFromIntention", false);
        }

        carBrandSelectModel =
                SCApplication.getApplication().getPreferenceConfig().getConfig(SCCarBrandSelectModel.class);

        if (isFromAddCar || isFromSub || isFromIntention) {
            /**
             * 来自添加 品牌 筛选
             */
            if (carBrandSelectModel != null && carBrandSelectModel.getAddTypes() != null) {
                recommendBrands = carBrandSelectModel.getAddTypes();
            } else {
                String JsonData = new GetJsonDataUtil().getJson(this, "brand.json");
                recommendBrands = parseData(JsonData);//用Gson 转成实体
            }
        } else {
            /**
             * 来自搜索 品牌 筛选
             */
            if (carBrandSelectModel != null && carBrandSelectModel.getSelectTypes() != null) {
                recommendBrands = carBrandSelectModel.getSelectTypes();
            } else {
                String JsonData = new GetJsonDataUtil().getJson(this, "brand.json");
                recommendBrands = parseData(JsonData);//用Gson 转成实体
            }
        }
    }

    /**
     * 解析json
     * @param result
     * @return
     */
    public static ArrayList<SCCarBrandResponse> parseData(String result) {
        ArrayList<SCCarBrandResponse> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                SCCarBrandResponse entity = gson.fromJson(data.optJSONObject(i).toString(), SCCarBrandResponse.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }

    private void initViews() {
        rl_back = findViewById(R.id.rl_back);
        rl_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        secondDrawerLayout = (SCCustomDrawerLayout) findViewById(R.id.secondDrawerLayout);
        llSecondContent = (LinearLayout) findViewById(R.id.llSecondContent);

        secondDrawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {

            }

            @Override
            public void onDrawerOpened(View drawerView) {
                secondDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                secondDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });

        thirdDrawerLayout = (SCCustomDrawerLayout) findViewById(R.id.thirdDrawerLayout);
        llthirdContent = (LinearLayout) findViewById(R.id.llthirdContent);

        thirdDrawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {

            }

            @Override
            public void onDrawerOpened(View drawerView) {
                thirdDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                secondDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                secondDrawerLayout.openDrawer(llSecondContent);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                thirdDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                secondDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });

        tvSeries = (TextView) findViewById(R.id.tvSeries);
        tvSeries.setOnClickListener(this);
        tvSpecies = (TextView) findViewById(R.id.tvSpecies);
        tvSpecies.setOnClickListener(this);
        if (isFromAddCar) {
            tvSeries.setVisibility(View.GONE);
            tvSpecies.setVisibility(View.GONE);
        }

        mFirstManager = new LinearLayoutManager(this);
        firstListView = (RecyclerView) findViewById(R.id.rv);
        firstListView.setLayoutManager(mFirstManager);

        mSecondManager = new LinearLayoutManager(this);
        secondListView = (RecyclerView) findViewById(R.id.rvSecond);
        secondListView.setLayoutManager(mSecondManager);
        secondAdapter = new SCSecondRightSelectViewAdapter(this, mSeconds, isFromAddCar);
        secondListView.setAdapter(secondAdapter);
        secondAdapter.setCallbackListener(new SCSecondRightSelectViewAdapter.CallbackListener() {
            @Override
            public void itemClick(int position) {
                if (isFromAddCar) {
                    for (int i = 0; i < mSeconds.size(); i++) {
                        mSeconds.get(i).setSelect(false);
                    }
                    mSeconds.get(position).setSelect(true);
                    secondAdapter.notifyDataSetChanged();

                    if (!thirdDrawerLayout.isDrawerOpen(llthirdContent)) {
                        thirdDrawerLayout.openDrawer(llthirdContent);
                    }
                    requestTpye = THIRD;
                    getRequest(mSeconds.get(position).getId());
                    series = mSeconds.get(position);
                } else {
                    if (isFromIntention) {
                        series = mSeconds.get(position);
                        species = null;
//                        jump2ChooseCar(position);
                    } else {
                        series = mSeconds.get(position);
                        species = null;
                        finishOkActivity();
                    }
                }
            }

            @Override
            public void open(int position) {
                for (int i = 0; i < mSeconds.size(); i++) {
                    mSeconds.get(i).setSelect(false);
                }
                mSeconds.get(position).setSelect(true);
                secondAdapter.notifyDataSetChanged();

                if (!thirdDrawerLayout.isDrawerOpen(llthirdContent)) {
                    thirdDrawerLayout.openDrawer(llthirdContent);
                }
                requestTpye = THIRD;
                getRequest(mSeconds.get(position).getId());
                series = mSeconds.get(position);
            }
        });
        secondListView.addItemDecoration(new SectionDecoration(this, mSeconds));

        mThirdManager = new LinearLayoutManager(this);
        thirdListView = (RecyclerView) findViewById(R.id.rvThird);
        thirdListView.setLayoutManager(mThirdManager);
        thirdAdapter = new SCThirdRightSelectViewAdapter(this, mThirds);
        thirdListView.setAdapter(thirdAdapter);
        thirdAdapter.setCallbackListener(new SCThirdRightSelectViewAdapter.CallbackListener() {
            @Override
            public void itemClick(int position) {
                if (isFromIntention && !isFromAddCar) {
                    species = mThirds.get(position);
//                    jump2ChooseCar(position);
                } else {
                    species = mThirds.get(position);
                    finishOkActivity();
                }
            }
        });
        thirdListView.addItemDecoration(new SectionDecoration(this, mThirds));

        /**
         * 关闭手势滑动
         */
        secondDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        thirdDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);

        WindowManager wm = getWindowManager();//获取屏幕宽高
        int width1 = wm.getDefaultDisplay().getWidth();
        int height1 = wm.getDefaultDisplay().getHeight();
        ViewGroup.LayoutParams para= llSecondContent.getLayoutParams();//获取drawerlayout的布局
        para.width=width1/4 * 3;//修改宽度
        para.height=height1;//修改高度
        llSecondContent.setLayoutParams(para); //设置修改后的布局。

        ViewGroup.LayoutParams para1= llthirdContent.getLayoutParams();//获取drawerlayout的布局
        para1.width=width1/2;//修改宽度
        para1.height=height1;//修改高度
        llthirdContent.setLayoutParams(para1); //设置修改后的布局。

        //获取所有品牌
        getRequest(0L);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvSeries:
                //款式不限
                series = null;
                species = null;
                finishOkActivity();
                break;
            case R.id.tvSpecies:
                //系列不限
                species = null;
                finishOkActivity();
                break;
        }
    }

    private void getRequest(Long id) {
        loadingDialog.show();
        Map<String,Object> params = new HashMap<>();
        params.put("id",id);
        HttpHelper.getInstance().appendUrl(HttpUrl.GET_ALL_BRANDS)
                .addGetParam(params)
                .get(new HttpCallBack<SCCarBrandResponse>(this) {
                    @Override
                    public void onSuccessed(SCCarBrandResponse result) {
                        if (loadingDialog != null){
                            loadingDialog.dismiss();
                        }
                        if (requestTpye == FIRST) {
                            List<SCCarBrandResponse> list = (List<SCCarBrandResponse>) result.getData();
                            mBrands.clear();
                            for (int i = 0; i < list.size(); i++) {
                                ItemBean itemBean = new ItemBean();
                                itemBean.setName(list.get(i).getName());//设置城市名称
                                itemBean.setId(list.get(i).getId());//设置城市id
                                itemBean.setHeadLetter(list.get(i).getHeadLetter());
                                itemBean.setLogo(list.get(i).getLogo());
                                mBrands.add(itemBean);
                            }

                            ItemBean recommend = new ItemBean();
                            recommend.setRecommendBrands(recommendBrands);
//                    recommend.setHeadLetter("**");
                            mBrands.add(0, recommend);
                            if(!isBrandLimit){
                                if (!isFromAddCar && !isFromSub) {
                                    ItemBean itemBean = new ItemBean();
                                    itemBean.setName("不限");//设置城市名称
                                    itemBean.setId(-1L);//设置城市id
                                    itemBean.setHeadLetter("*");
                                    mBrands.add(0, itemBean);
                                }
                            }

                            setFirstView();
                        }

                        else if (requestTpye == SECOND) {
                            List<SCCarBrandResponse> list = (List<SCCarBrandResponse>) result.getData();
                            mSeconds.clear();
                            for (int i = 0; i < list.size(); i++) {
                                for (int j = 0; j < list.get(i).getChildren().size(); j ++) {
                                    ItemBean itemBean = new ItemBean();
                                    itemBean.setName(list.get(i).getChildren().get(j).getName());
                                    itemBean.setId(list.get(i).getChildren().get(j).getId());
                                    itemBean.setHeadLetter(list.get(i).getName());
                                    mSeconds.add(itemBean);
                                }
                            }
                            setSecondView();
                        }
                        else if (requestTpye == THIRD) {
                            List<SCCarBrandResponse> list = (List<SCCarBrandResponse>) result.getData();
                            mThirds.clear();
                            for (int i = 0; i < list.size(); i++) {
                                for (int j = 0; j < list.get(i).getChildren().size(); j ++) {
                                    ItemBean itemBean = new ItemBean();
                                    itemBean.setName(list.get(i).getChildren().get(j).getName());//设置城市名称
                                    itemBean.setId(list.get(i).getChildren().get(j).getId());//设置城市名称
                                    itemBean.setHeadLetter(list.get(i).getName());
                                    mThirds.add(itemBean);
                                }
                            }
                            setThirdView();
                        }
                    }

                    @Override
                    public void onFailured(String errorCode, String errMsg) {
                        if (loadingDialog != null){
                            loadingDialog.dismiss();
                        }
                    }
                });
    }

    private void setFirstView() {
        boolean isAdd = isFromAddCar || isFromSub || isFromIntention ? true : false;   //是否来自添加
        firstAdapter = new BrandAdapter(this, mBrands, isAdd);
        firstListView.setAdapter(firstAdapter);
        firstAdapter.setCallbackListener(new BrandAdapter.CallbackListener() {
            @Override
            public void itemClick(int position) {
                if (mBrands.get(position).getId() == -1) {
                    /**
                     * 点击了不限
                     */
                    brand = null;
                    series = null;
                    species = null;
                    finishOkActivity();
                } else {
                    for (int i = 0; i < mBrands.size(); i++) {
                        mBrands.get(i).setSelect(false);
                    }
                    mBrands.get(position).setSelect(true);
                    firstAdapter.notifyDataSetChanged();

                    if (secondDrawerLayout.isDrawerOpen(llSecondContent)) {
                        if (thirdDrawerLayout.isDrawerOpen(llthirdContent)) {
                            thirdDrawerLayout.closeDrawers();
                        }
                    } else {
                        secondDrawerLayout.openDrawer(llSecondContent);
                    }
                    requestTpye = SECOND;
                    getRequest(mBrands.get(position).getId());
                    brand = mBrands.get(position);
                }
            }

            @Override
            public void itemRecommendClick(int position) {
                if (secondDrawerLayout.isDrawerOpen(llSecondContent)) {
                    if (thirdDrawerLayout.isDrawerOpen(llthirdContent)) {
                        thirdDrawerLayout.closeDrawers();
                    }
                } else {
                    secondDrawerLayout.openDrawer(llSecondContent);
                }
                requestTpye = SECOND;
                getRequest(recommendBrands.get(position).getId());
                brand = new ItemBean();
                brand.setId(recommendBrands.get(position).getId());
                brand.setName(recommendBrands.get(position).getName());
                brand.setLogo(recommendBrands.get(position).getLogo());
            }
        });
        firstListView.addItemDecoration(new TitleItemDecoration(this, mBrands));

        //使用indexBar
        mTvSideBarHint = (TextView) findViewById(R.id.tvSideBarHint);//HintTextView
        mIndexBar = (IndexBar) findViewById(R.id.indexBar);//IndexBar
        mIndexBar.setmPressedShowTextView(mTvSideBarHint)//设置HintTextView
                .setNeedRealIndex(false)//设置需要真实的索引
                .setmLayoutManager(mFirstManager)//设置RecyclerView的LayoutManager
                .setmSourceDatas(mBrands);//设置数据源
    }

    private void setSecondView() {
        if (!isFromAddCar) {
            tvSeries.setVisibility(View.VISIBLE);
        }
        secondAdapter.notifyDataSetChanged();
    }
    private void setThirdView() {
        if (!isFromAddCar) {
            tvSpecies.setVisibility(View.VISIBLE);
        }
        thirdAdapter.notifyDataSetChanged();
    }


    /**
     * 结束当前选择
     */
    private void finishOkActivity() {

        /**
         * 判断有没有相同项，
         * 如有则将相同的那项放第一位
         */
        if (brand != null) {
            boolean isAdd = true;
            SCCarBrandResponse carBrand = new SCCarBrandResponse();
            carBrand.setId(brand.getId());
            carBrand.setLogo(brand.getLogo());
            carBrand.setName(brand.getName());
            for (int i = 0; i < recommendBrands.size(); i++) {
                if (recommendBrands.get(i).getId().equals(brand.getId())) {
                    recommendBrands.remove(i);
                    recommendBrands.add(0, carBrand);
                    isAdd = false;
                    break;
                }
            }
            if (isAdd) {
                recommendBrands.add(0, carBrand);
                if (recommendBrands.size() > 5) {
                    recommendBrands.remove(5);
                }
            }

            if (carBrandSelectModel == null) {
                carBrandSelectModel = new SCCarBrandSelectModel();
            }
            if (isFromSub || isFromAddCar || isFromIntention) {
                carBrandSelectModel.setAddTypes(recommendBrands);
            } else {
                carBrandSelectModel.setSelectTypes(recommendBrands);
            }
            SCApplication.getApplication().getPreferenceConfig().setConfig(carBrandSelectModel);
        }
        Intent intent = new Intent();
        intent.putExtra("brand", brand);
        intent.putExtra("series", series);
        intent.putExtra("species", species);
        intent.putExtra("from", from);
        setResult(Activity.RESULT_OK,intent);
        finish();
    }


}